package remote.mvc.delegates
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.Socket;
	import flash.utils.ByteArray;
	
	
	
	/**
	 * Socket通讯代理,一般情况，此类的实例会单独存在 
	 * @createDate 2011-2-28
	 * @author 徐俊杰
	 */
	public class SocketDelegate
	{
		private var _host:String;
		private var _port:int;
		
		private var _socket:Socket;
		public function SocketDelegate(host:String, port:int)
		{
			super();
			_host = host;
			_port = port;
			
		}
		
		public function connect():void
		{
			_socket.connect(_host, _port);
			_socket.addEventListener(Event.CONNECT, connectHandler);

		}
		
		public function send(data:ByteArray):void
		{
			if(_socket.connected)
				_socket.writeBytes(data);
		}
		
		public function stop():void
		{
			_socket.removeEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
			_socket.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			_socket.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			_socket.close();
		}
		
		private function connectHandler(e:Event):void
		{
			_socket.removeEventListener(Event.CONNECT, connectHandler);
			_socket.addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
			_socket.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
		}
		
		private function socketDataHandler(e:ProgressEvent):void
		{
			var data:Object = new Object();					//根据协议读一个完整的对象
			//getHandler(type).result(data);
		}

		private function ioErrorHandler(e:IOErrorEvent):void
		{
			trace(e.text);
		}
		
		private function securityErrorHandler(e:SecurityErrorEvent):void
		{
			trace(e.text);
		}
		
	}
}